package com.it.cloud.itagent.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.NoArgsConstructor;

/**
 * @author 司马缸砸缸了
 * @description 客户端TEST
 * @date 2019/8/1 10:53
 */


@NoArgsConstructor
public class NettyClient {

    private EventLoopGroup group = new NioEventLoopGroup();

    /**
     * 连接方法
     */
    public void connect() {

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group).channel(NioSocketChannel.class);
            bootstrap.option(ChannelOption.TCP_NODELAY, true);
            // bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            bootstrap.handler(new NettyClientInitializer());
            Channel channel = bootstrap.connect("127.0.0.1", 2222).sync().channel();
            // 发送json字符串
            String msg = "{\"name\":\"admin\",\"age\":27}\n";
            channel.writeAndFlush(msg);
            channel.closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }

    /**
     * 主动关闭
     */
    public void close() {
        group.shutdownGracefully();
    }

    /**
     * 测试入口
     *
     * @param args
     */
    public static void main(String[] args) {
        NettyClient nettyClient = new NettyClient();
        nettyClient.connect();
    }


}
